/**
 * 数据血缘相关API服务
 */

import api from './api';

// 类型定义
export interface Task {
  id: number;
  name: string;
  statement?: string;
  type?: string;
  enabled: boolean;
  note?: string;
  create_time?: string;
  update_time?: string;
}

export interface LineageNode {
  id: string;
  type: string;
  database?: string;
  table: string;
  full_name: string;
  columns?: string[];
  properties?: Record<string, any>;
  position?: { x: number; y: number };
}

export interface LineageEdge {
  id: string;
  source: string;
  target: string;
  type: string;
  column_mapping?: Record<string, string>;
  properties?: Record<string, any>;
}

export interface DataLineage {
  id?: number;
  task_id: number;
  task_name: string;
  nodes: LineageNode[];
  edges: LineageEdge[];
  node_count: number;
  edge_count: number;
  status: string;
  created_at?: string;
  updated_at?: string;
}

export interface LineageAnalysisRequest {
  task_id: number;
  force_refresh?: boolean;
}

export interface LineageAnalysisResponse {
  task_id: number;
  task_name: string;
  analysis_success: boolean;
  lineage?: DataLineage;
  error_message?: string;
  processing_time: number;
}

export interface LineageGraphData {
  nodes: Array<{
    id: string;
    label: string;
    type: string;
    data: any;
    position: { x: number; y: number };
    style: any;
  }>;
  edges: Array<{
    id: string;
    source: string;
    target: string;
    type: string;
    data: any;
    style: any;
  }>;
  layout: string;
}

export interface ApiResponse<T> {
  code: number;
  message: string;
  success: boolean;
  data: T;
  timestamp: string;
}

export interface PaginatedResponse<T> {
  code: number;
  message: string;
  success: boolean;
  data: T[];
  pagination: {
    current: number;
    pageSize: number;
    total: number;
    totalPages: number;
  };
  timestamp: string;
}

/**
 * 数据血缘服务类
 */
export class LineageService {
  
  /**
   * 获取任务列表
   */
  static async getTasks(params: {
    skip?: number;
    limit?: number;
    enabled_only?: boolean;
  } = {}): Promise<PaginatedResponse<Task>> {
    const response = await api.get('/v1/tasks/', { params });
    return response.data;
  }

  /**
   * 获取有SQL语句的任务列表
   */
  static async getTasksWithStatements(params: {
    skip?: number;
    limit?: number;
  } = {}): Promise<PaginatedResponse<Task>> {
    const response = await api.get('/v1/tasks/with-statements', { params });
    return response.data;
  }

  /**
   * 根据ID获取任务详情
   */
  static async getTask(taskId: number): Promise<ApiResponse<Task>> {
    const response = await api.get(`/v1/tasks/${taskId}`);
    return response.data;
  }

  /**
   * 获取任务的SQL语句
   */
  static async getTaskStatement(taskId: number): Promise<ApiResponse<any>> {
    const response = await api.get(`/v1/tasks/${taskId}/statement`);
    return response.data;
  }

  /**
   * 分析任务的数据血缘
   */
  static async analyzeTaskLineage(
    request: LineageAnalysisRequest
  ): Promise<ApiResponse<LineageAnalysisResponse>> {
    const response = await api.post('/v1/lineage/analyze', request);
    return response.data;
  }

  /**
   * 获取任务的数据血缘信息
   */
  static async getTaskLineage(taskId: number): Promise<ApiResponse<DataLineage>> {
    const response = await api.get(`/v1/lineage/${taskId}`);
    return response.data;
  }

  /**
   * 获取血缘图数据
   */
  static async getLineageGraphData(taskId: number): Promise<ApiResponse<LineageGraphData>> {
    const response = await api.get(`/v1/lineage/${taskId}/graph`);
    return response.data;
  }

  /**
   * 删除任务的血缘信息
   */
  static async deleteTaskLineage(taskId: number): Promise<ApiResponse<any>> {
    const response = await api.delete(`/v1/lineage/${taskId}`);
    return response.data;
  }

  /**
   * 搜索任务
   */
  static async searchTasks(
    keyword: string,
    params: {
      skip?: number;
      limit?: number;
    } = {}
  ): Promise<PaginatedResponse<Task>> {
    const response = await api.get(`/v1/tasks/search/${keyword}`, { params });
    return response.data;
  }

  /**
   * 获取缓存的血缘数据
   */
  static async getCachedLineageData(): Promise<ApiResponse<any>> {
    const response = await api.get('/v1/lineage/cached-lineage');
    return response.data;
  }

  /**
   * 解析数据库生成血缘数据
   */
  static async parseDatabaseLineage(): Promise<ApiResponse<any>> {
    const response = await api.post('/v1/lineage/parse-database');
    return response.data;
  }

  /**
   * 启动数据库解析任务（支持暂停/恢复）
   */
  static async startDatabaseParsing(): Promise<ApiResponse<{ taskId: string }>> {
    const response = await api.post('/v1/lineage/start-parsing');
    return response.data;
  }

  /**
   * 暂停数据库解析任务
   */
  static async pauseDatabaseParsing(taskId: string): Promise<ApiResponse<any>> {
    const response = await api.post(`/v1/lineage/pause-parsing/${taskId}`);
    return response.data;
  }

  /**
   * 恢复数据库解析任务
   */
  static async resumeDatabaseParsing(taskId: string): Promise<ApiResponse<any>> {
    const response = await api.post(`/v1/lineage/resume-parsing/${taskId}`);
    return response.data;
  }

  /**
   * 取消数据库解析任务
   */
  static async cancelDatabaseParsing(taskId: string): Promise<ApiResponse<any>> {
    const response = await api.post(`/v1/lineage/cancel-parsing/${taskId}`);
    return response.data;
  }

  /**
   * 获取数据库解析任务状态
   */
  static async getDatabaseParsingStatus(taskId: string): Promise<ApiResponse<{
    status: 'running' | 'paused' | 'completed' | 'failed' | 'cancelled';
    progress: number;
    currentStage?: string;
    currentTable?: string;
    processedTables?: number;
    totalTables?: number;
    estimatedTimeRemaining?: number;
    errorMessage?: string;
  }>> {
    const response = await api.get(`/v1/lineage/parsing-status/${taskId}`);
    return response.data;
  }

  /**
   * 测试数据库连接
   */
  static async testDatabaseConnection(): Promise<ApiResponse<any>> {
    const response = await api.post('/v1/lineage/test-connection');
    return response.data;
  }

  /**
   * 批量分析所有任务
   */
  static async batchAnalyzeAllTasks(request: { force_refresh?: boolean } = {}): Promise<ApiResponse<any>> {
    const response = await api.post('/v1/lineage/analyze-all', request);
    return response.data;
  }

  /**
   * 重建缓存数据
   */
  static async rebuildCache(): Promise<ApiResponse<any>> {
    const response = await api.post('/v1/lineage/rebuild-cache');
    return response.data;
  }
}
